<template>
  <div>
    <el-upload action="/api/v1/upload/picture"
               :on-exceed="handleExceed"
               :data="uploadParams"
               ref="upload"
               drag
               :limit="limit"
               :list-type="'picture-card'"
               :http-request="handleUpload"
               :before-upload="beforeUpload"
               :file-list="fileList">
      <i class="el-icon-plus"></i>
      <div slot="file"
           slot-scope="{file}">
        <img class="el-upload-list__item-thumbnail"
             :src="file.url"
             alt="">
        <span class="el-upload-list__item-actions">
          <span class="el-upload-list__item-preview"
                @click="handlePictureCardPreview(file)">
            <i class="el-icon-zoom-in"></i>
          </span>
          <span v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleDownload(file)">
            <i class="el-icon-download"></i>
          </span>
          <span v-if="!disabled"
                class="el-upload-list__item-delete"
                @click="handleRemove(file)">
            <i class="el-icon-delete"></i>
          </span>
        </span>
      </div>
    </el-upload>
    <el-dialog :visible.sync="dialogVisible">
      <img width="100%"
           :src="imgUrl"
           alt="">
    </el-dialog>
  </div>

</template>

<script>
import { calculateSHA512 } from '@/utils/encrypt';
import { uploadFileToCos, deleteUploadFile } from "@/api/cos"
import { getAccessToken } from "@/utils/auth"
export default {
  props: {
    editUrl: {
      type: String,
      required: false
    },
  },
  watch: {
    editUrl: {
      immediate: true,
      handler (val) {
        // 如果传递了url
        if (val) {
          // 清空fileList
          this.fileList = [];

          // 创建一个 file 对象
          const fileObj = {
            name: 'edited-image',
            url: val
          };

          // 将 fileObj 添加到 fileList 中
          this.fileList.push(fileObj);
          this.imgUrl = val
          this.$store.commit("upload/SETIMGURL", val)

        }
      }
    }
  },
  data () {
    return {
      fileList: [],
      imgUrl: "",
      uploadParams: {
        img: null
      },
      dialogVisible: false,
      disabled: false,
      limit: 1,
      currentFile: null
    };
  },
  computed: {

  },
  methods: {
    handleExceed (files, fileList) {
      console.log("超出限制")
      // 文件数量超过限制的回调函数
      this.$message.warning(`只能上传 ${this.limit} 个文件`);
    },
    async handleRemove (file) {
      console.log(file);
      // cos清空数据0
      if (file.status == 'success') {
        if (this.imgUrl) {
          // 整理数据
          const formData = new FormData()
          formData.append('url', this.imgUrl)
          // 检测是否可以删除
          const res = await this.$API.upload.DetectCosRemove(formData)
          if (res.status == 200) {
            // 删除多余图片
            const response = await deleteUploadFile('picture/' + file.name)
            if (response.statusCode == 200 || response.statusCode == 204) {
              this.fileList = []

              this.imgUrl = ""
            }
          }
          // 如果其他资源引用了 
          else if (res.status == 422) {
            this.fileList = []

            this.imgUrl = ""
          }
        }
        // 本地清空数据
        // const index = this.fileList.indexOf(file);
        // console.log(index, this.imgList[index])

        // if (index !== -1) {
        //   // 整理数据
        //   const formData = new FormData()
        //   formData.append('url', this.imgList[index])
        //   // 删除多余图片
        //   const res = await this.$API.upload.DeleteAlreadyUploadFile(formData)
        //   if (res.status == 200 || res.status == 422) {
        //     this.fileList.splice(index, 1);

        //     this.imgList.splice(index, 1);

        //   }
        // }
      }

    },
    // 放大缩略图
    handlePictureCardPreview (file) {
      this.dialogImageUrl = file.url;
      this.dialogVisible = true;
    },
    handleDownload (file) {
      console.log(file);
    },
    async handleUpload () {
      console.log('file', this.currentFile);
      // 格式校验
      const allowedExtensions = ['.jpg', '.jpeg', '.png', '.gif'];
      const allowedMimeTypes = ['image/jpeg', 'image/png', 'image/gif'];

      const fileExtension = this.currentFile.name.substring(this.currentFile.name.lastIndexOf('.')).toLowerCase();
      const fileMimeType = this.currentFile.type;
      // 检查文件扩展名
      if (!allowedExtensions.includes(fileExtension)) {
        this.$message.error('只能上传 JPG、JPEG、PNG 或 GIF 格式的图片');
        this.fileList = []
        return;
      }

      // 检查文件 MIME 类型
      if (!allowedMimeTypes.includes(fileMimeType)) {
        this.$message.error('只能上传 JPG、JPEG、PNG 或 GIF 格式的图片');
        this.fileList = []
        return;
      }
      // cos存储
      try {
        const response = await uploadFileToCos(this.currentFile, this.currentFile.name);
        console.log(response);
        this.imgUrl = 'http://' + response.Location
        // 上传成功后将 URL 存储到 Vuex 中
        this.$store.commit("upload/SETIMGURL", this.imgUrl);
        // 上传成功后将文件添加到 fileList 中
        this.fileList.push({
          name: this.currentFile.name,
          url: this.imgUrl
        });
        // 清空当前文件
        this.currentFile = null;
      } catch (error) {
        console.error(error);
        this.$message.error('上传失败');
      }
      // 本地存储
      // const fileReader = new FileReader()
      // // 以8192字节的形式读取文件
      // const chunkSize = 8192;
      // let currentByte = 0;
      // // 文件读取
      // fileReader.onload = async () => {
      //   const arrayBuffer = fileReader.result;
      //   const uint8Array = new Uint8Array(arrayBuffer);
      //   // 格式转换
      //   const fileBlob = new Blob([arrayBuffer], { type: this.currentFile.type });
      //   // 生成hash值
      //   const file_hash = await calculateSHA512(fileBlob);
      //   const datas = this.$qs.stringify({ 'file_hash': file_hash })
      //   console.log(file_hash, datas)
      //   try {
      //     // 验证文件是否存在
      //     const res = await this.$API.upload.CheckExist(datas)
      //     console.log(res)

      //     // 如果存在秒传地址
      //     if (res && res.status == 200) {
      //       // this.videoUrl = res.data.url

      //       this.$store.commit("upload/SETIMGURL", res.data.url)
      //       console.log('imgurl', this.$store.state.upload.img_url)
      //       return;
      //     }
      //     // 整理数据
      //     // const formData = new FormData()
      //     formData.append('img', this.currentFile)
      //     // 上传图片
      //     const response = await this.$API.upload.uploadImage(formData)
      //     console.log(response)
      //     if (response.status == 200) {
      //       // this.fileList.push(this.currentFile)
      //       this.imgUrl = response.data.url
      //       // 数据传递
      //       this.$store.commit("upload/SETIMGURL", res.data.url)

      //     }
      //   } catch (error) {
      //     this.$message.error("文件检查请求失败")
      //     return;
      //   }
      // }
      // fileReader.readAsArrayBuffer(this.currentFile);


    },
    async beforeUpload (file) {
      console.log(file)
      this.currentFile = file
      // 阻止自动上传
      return false
    },
  }
};
</script>
